<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>pdf查看</title>
  <!-- ====================================== 关键步骤 =============================================== -->
  <!-- uni 的 SDK -->
  <!-- 需要把 uni.webview.1.5.4.js 下载到自己的服务器 -->
  <script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>

  <!-- 也可以使用 自己搭建的 pdf.js -->
  <!-- <script src="../js_sdk/pdf.min.js"></script> -->
  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
    }

    #pdf-container {
      margin: 20px auto;
      max-width: 800px;
    }

    canvas {
      border: 1px solid #ddd;
      width: 100%;
      height: auto;
    }
  </style>
</head>

<body>
  <h2>PDF 预览</h2>
  <div id="pdf-container"></div>

  <script>
    document.addEventListener('UniAppJSBridgeReady', async function () {
      // 页面需要做的事情在这里写
      await uni.postMessage({
        data: {
          action: 'message'
        }
      });
      // ==================================================================
      // pdf 开始
      // ==================================================================

      document.addEventListener('DOMContentLoaded', async () => {
        // 这行必须写，否则 worker 找不到
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
        const url = '/doc/demo.pdf'; // 示例 PDF

        try {
          // ✅ 使用 pdfjsLib（注意：变量名是 pdfjsLib）
          const loadingTask = pdfjsLib.getDocument(url);
          const pdf = await loadingTask.promise;
          console.log(`PDF 加载成功，共 ${pdf.numPages} 页`);

          const page = await pdf.getPage(1);
          const scale = 2.0;
          const viewport = page.getViewport({ scale });

          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          canvas.height = viewport.height;
          canvas.width = viewport.width;

          document.getElementById('pdf-container').appendChild(canvas);

          await page.render({
            canvasContext: context,
            viewport: viewport
          }).promise;

          console.log('第一页渲染完成');
        } catch (error) {
          console.error('PDF 加载失败:', error);
          document.getElementById('pdf-container').innerHTML = `
              <p style="color:red">加载失败: ${error.message}</p>
            `;
        }
      });
      // ==================================================================
      // pdf 结束
      // ==================================================================
    })
  </script>
</body>

</html>